﻿/******************************************************************************
 *  All Rights Reserved , Copyright (C) 2012 , EricHu. 
 *  作    者： EricHu
 *  创建时间： 2012-5-10 10:00:50
 ******************************************************************************/

using System;
using System.Collections.Generic;
using System.Data;

namespace RDIFramework.ServiceAdapter
{
    using RDIFramework.BusinessEntity;
    using RDIFramework.Utilities;  

    /// <summary>
    /// CiFileManager
    /// 文件表
    ///
    /// 修改纪录
    ///
    ///		2012-03-02 版本：1.0 EricHu 创建主键。
    ///
    /// 版本：1.0
    ///
    /// <author>
    ///		<name>EricHu</name>
    ///		<date>2012-03-02</date>
    /// </author>
    /// </summary>
    public partial class CiFileManager : DbCommonManager, IDbCommonManager
    {
        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        public CiFileManager()
        {
            if (base.dbProvider == null)
            {
                base.dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType, SystemInfo.RDIFrameworkDbConection);
            }
            base.CurrentTableName = CiFileTable.TableName;
        }

        /// <summary>
        /// 构造函数
        /// <param name="tableName">指定表名</param>
        /// </summary>
        public CiFileManager(string tableName)
        {
            base.CurrentTableName = tableName;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbProvider">数据库连接</param>
        public CiFileManager(IDbProvider dbProvider)
            : this()
        {
            DBProvider = dbProvider;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userInfo">操作员信息</param>
        public CiFileManager(UserInfo userInfo)
            : this()
        {
            UserInfo = userInfo;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbProvider">数据库连接</param>
        /// <param name="userInfo">操作员信息</param>
        public CiFileManager(IDbProvider dbProvider, UserInfo userInfo)
            : this(dbProvider)
        {
            UserInfo = userInfo;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbProvider">数据库连接</param>
        /// <param name="userInfo">操作员信息</param>
        /// <param name="tableName">指定表名</param>
        public CiFileManager(IDbProvider dbProvider, UserInfo userInfo, string tableName)
            : this(dbProvider, userInfo)
        {
            base.CurrentTableName = tableName;
        }
        #endregion

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="fileEntity">实体</param>
        /// <returns>主键</returns>
        public string Add(CiFileEntity fileEntity)
        {
            return this.AddEntity(fileEntity);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="fileEntity">实体</param>
        /// <param name="identity">自增量方式</param>
        /// /// <param name="returnId">返回主鍵</param>
        /// <returns>主键</returns>
        public string Add(CiFileEntity fileEntity, bool identity, bool returnId)
        {
            this.Identity = identity;
            this.ReturnId = returnId;
            return this.AddEntity(fileEntity);
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="CiFileTable">实体</param>
        public int Update(CiFileEntity fileEntity)
        {
            return this.UpdateEntity(fileEntity);
        }

        /// <summary>
        /// 添加实体
        /// </summary>
        /// <param name="fileEntity">实体</param>
        public string AddEntity(CiFileEntity fileEntity)
        {
            string sequence = string.Empty;
            if (String.IsNullOrEmpty(fileEntity.SortCode))
            {
                CiSequenceManager sequenceManager = new CiSequenceManager(DBProvider, this.Identity);
                sequence = sequenceManager.GetSequence(this.CurrentTableName);
                fileEntity.SortCode = sequence;
            }
            if (fileEntity.Id is string)
            {
                this.Identity = false;
            }
            SQLBuilder sqlBuilder = new SQLBuilder(DBProvider, this.Identity, false);
            sqlBuilder.BeginInsert(this.CurrentTableName, CiFileTable.FieldId);
            if (!this.Identity)
            {
                if (String.IsNullOrEmpty(fileEntity.Id))
                {
                    fileEntity.Id = BusinessLogic.NewGuid();
                }

                sqlBuilder.SetValue(CiFileTable.FieldId, fileEntity.Id);
            }
            else
            {
                if (!this.ReturnId && DBProvider.CurrentDbType == CurrentDbType.Oracle)
                {
                    sqlBuilder.SetFormula(CiFileTable.FieldId, "SEQ_" + this.CurrentTableName.ToUpper() + ".NEXTVAL ");
                }
                else
                {
                    if (this.Identity && DBProvider.CurrentDbType == CurrentDbType.Oracle)
                    {
                        if (string.IsNullOrEmpty(fileEntity.Id))
                        {
                            if (string.IsNullOrEmpty(sequence))
                            {
                                CiSequenceManager sequenceManager = new CiSequenceManager(DBProvider, this.Identity);
                                sequence = sequenceManager.GetSequence(this.CurrentTableName);
                            }
                            fileEntity.Id = sequence;
                        }
                        sqlBuilder.SetValue(CiFileTable.FieldId, fileEntity.Id);
                    }
                }
            }
            this.SetEntity(sqlBuilder, fileEntity);
            if (UserInfo != null)
            {
                sqlBuilder.SetValue(CiFileTable.FieldCreateUserId, UserInfo.Id);
                sqlBuilder.SetValue(CiFileTable.FieldCreateBy, UserInfo.RealName);
            }
            sqlBuilder.SetDBNow(CiFileTable.FieldCreateOn);
            /*
            if (UserInfo != null)
            {
                sqlBuilder.SetValue(CiFileTable.FieldModifiedUserId, UserInfo.Id);
                sqlBuilder.SetValue(CiFileTable.FieldModifiedBy, UserInfo.RealName);
            }
            sqlBuilder.SetDBNow(CiFileTable.FieldModifiedOn);
             */
            if (DBProvider.CurrentDbType == CurrentDbType.SqlServer && this.Identity)
            {
                sequence = sqlBuilder.EndInsert().ToString();
            }
            else
            {
                sqlBuilder.EndInsert();
            }
            return sequence;
        }

        /// <summary>
        /// 更新实体
        /// </summary>
        /// <param name="fileEntity">实体</param>
        public int UpdateEntity(CiFileEntity fileEntity)
        {
            SQLBuilder sqlBuilder = new SQLBuilder(DBProvider);
            sqlBuilder.BeginUpdate(this.CurrentTableName);
            this.SetEntity(sqlBuilder, fileEntity);
            if (UserInfo != null)
            {
                sqlBuilder.SetValue(CiFileTable.FieldModifyUserId, UserInfo.Id);
                sqlBuilder.SetValue(CiFileTable.FieldModifiedBy, UserInfo.RealName);
            }
            sqlBuilder.SetDBNow(CiFileTable.FieldModifiedOn);
            sqlBuilder.SetWhere(CiFileTable.FieldId, fileEntity.Id);
            return sqlBuilder.EndUpdate();
        }

        /// <summary>
        /// 设置实体
        /// </summary>
        /// <param name="CiFileTable">实体</param>
        private void SetEntity(SQLBuilder sqlBuilder, CiFileEntity fileEntity)
        {
            sqlBuilder.SetValue(CiFileTable.FieldFolderId, fileEntity.FolderId);
            sqlBuilder.SetValue(CiFileTable.FieldFileName, fileEntity.FileName);
            sqlBuilder.SetValue(CiFileTable.FieldFilePath, fileEntity.FilePath);
            sqlBuilder.SetValue(CiFileTable.FieldFileContent, fileEntity.FileContent);
            if (fileEntity.FileSize != null)
            {
                sqlBuilder.SetValue(CiFileTable.FieldFileSize, fileEntity.FileContent.Length);
            }
            else
            {
                sqlBuilder.SetValue(CiFileTable.FieldFileSize, fileEntity.FileSize);
            }

            sqlBuilder.SetValue(CiFileTable.FieldImageUrl, fileEntity.ImageUrl);
            sqlBuilder.SetValue(CiFileTable.FieldReadCount, fileEntity.ReadCount);
            sqlBuilder.SetValue(CiFileTable.FieldCategory, fileEntity.Category);
            sqlBuilder.SetValue(CiFileTable.FieldDescription, fileEntity.Description);
            sqlBuilder.SetValue(CiFileTable.FieldSortCode, fileEntity.SortCode);
            sqlBuilder.SetValue(CiFileTable.FieldDeleteMark, fileEntity.DeleteMark);
        }

        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>影响行数</returns>
        public int Delete(string id)
        {
            return this.Delete(CiFileTable.FieldId, id);
        }

         #region public CiFileTable GetEntity(string id) 获取信息
        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>数据权限</returns>
        public CiFileEntity GetEntity(string id)
        {
            string sqlQuery = string.Empty;
            sqlQuery = " SELECT " + CiFileTable.FieldId
                    + "        ," + CiFileTable.FieldFolderId
                    + "        ," + CiFileTable.FieldCategory
                    + "        ," + CiFileTable.FieldFileName
                    + "        ," + CiFileTable.FieldFilePath
                    + "        ," + CiFileTable.FieldImageUrl
                    + "        ," + CiFileTable.FieldFileSize
                    + "        ," + CiFileTable.FieldReadCount
                    + "        ," + CiFileTable.FieldDescription
                    + "        ," + CiFileTable.FieldEnabled
                    + "        ," + CiFileTable.FieldDeleteMark
                    + "        ," + CiFileTable.FieldSortCode
                    + "        ," + CiFileTable.FieldCreateUserId
                    + "        ," + CiFileTable.FieldCreateBy
                    + "        ," + CiFileTable.FieldCreateOn
                    + "        ," + CiFileTable.FieldModifyUserId
                    + "        ," + CiFileTable.FieldModifiedBy
                    + "        ," + CiFileTable.FieldModifiedOn
                        + " FROM " + this.CurrentTableName
                        + " WHERE " + CiFileTable.FieldId + " = " + DBProvider.GetParameter(CiFileTable.FieldId);
            DataTable dataTable = new DataTable(CiFileTable.TableName);
            DBProvider.Fill(dataTable, sqlQuery, new IDbDataParameter[] { DBProvider.MakeParameter(CiFileTable.FieldId, id) });
            CiFileEntity fileEntity = new CiFileEntity(dataTable);
            return fileEntity;
        }
        #endregion

        private int UpdateReadCount(string id)
        {
            // 阅读次数要加一
            SQLBuilder sqlBuilder = new SQLBuilder(DBProvider);
            sqlBuilder.BeginUpdate(CiFileTable.TableName);
            sqlBuilder.SetFormula(CiFileTable.FieldReadCount, CiFileTable.FieldReadCount + " + 1 ");
            sqlBuilder.SetWhere(CiFileTable.FieldId, id);
            return sqlBuilder.EndUpdate();
        }

        /// <summary>
        /// 从数据库中读取文件
        /// </summary>
        /// <param name="id">文件主键</param>
        /// <returns>文件</returns>
        public byte[] Download(string id)
        {
            // 阅读次数要加一
            this.UpdateReadCount(id);
            // 下载文件
            byte[] fileContent = null;
            string sqlQuery = " SELECT " + CiFileTable.FieldFileContent
                            + "   FROM " + CiFileTable.TableName
                            + "  WHERE " + CiFileTable.FieldId + " = " + DBProvider.GetParameter(CiFileTable.FieldId);
            IDataReader dataReader = null;
            try
            {
                dataReader = DBProvider.ExecuteReader(sqlQuery, new IDbDataParameter[] { DBProvider.MakeParameter(CiFileTable.FieldId, id)});
                if (dataReader.Read())
                {
                    fileContent = (byte[])dataReader[CiFileTable.FieldFileContent];
                }
            }
            catch (System.Exception ex)
            {
                // 在本地记录异常
                CiExceptionManager.LogException(DBProvider, UserInfo, ex);
            }
            finally
            {
                if (dataReader != null)
                {
                    dataReader.Close();
                }
            }
            return fileContent;
        }

        public string Upload(string folderId, string fileName, byte[] file, bool enabled)
        {
            // 检查是否已经存在
            string returnValue = this.GetId(CiFileTable.FieldFolderId, folderId, CiFileTable.FieldFileName, fileName);
            if (!String.IsNullOrEmpty(returnValue))
            {
                // 更新数据
                this.UpdateFile(returnValue, fileName, file);
            }
            else
            {
                // 添加数据
                CiFileEntity fileEntity = new CiFileEntity();
                fileEntity.FolderId = folderId;
                fileEntity.FileName = fileName;
                fileEntity.FileContent = file;
                fileEntity.Enabled = enabled ? 1:0;
                returnValue = this.AddEntity(fileEntity);
            }
            return returnValue;
        }

        #region public DataTable GetDTByFolder(string id) 获取信息
        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>数据表</returns>
        public DataTable GetDTByFolder(string id)
        {
            string sqlQuery = string.Empty;
            sqlQuery = " SELECT " + CiFileTable.FieldId
                    + "        ," + CiFileTable.FieldFolderId
                    + "        ," + CiFileTable.FieldFileName
                    + "        ," + CiFileTable.FieldFilePath
                    + "        ," + CiFileTable.FieldFileSize
                    + "        ," + CiFileTable.FieldReadCount
                    + "        ," + CiFileTable.FieldCategory
                    + "        ," + CiFileTable.FieldDescription
                    + "        ," + CiFileTable.FieldEnabled
                    + "        ," + CiFileTable.FieldSortCode
                    + "        ," + CiFileTable.FieldCreateUserId
                    + "        ," + CiFileTable.FieldCreateBy
                    + "        ," + CiFileTable.FieldCreateOn
                    + "        ," + CiFileTable.FieldModifyUserId
                    + "        ," + CiFileTable.FieldModifiedBy
                    + "        ," + CiFileTable.FieldModifiedOn
                    + "       , (SELECT " + CiFolderTable.FieldFolderName
                                + " FROM " + CiFolderTable.TableName
                                + " WHERE " + CiFolderTable.FieldId + " = " + CiFileTable.FieldFolderId + ") AS FolderFullName "
                    + " FROM " + CiFileTable.TableName
                    + " WHERE " + CiFileTable.FieldFolderId + " = " + DBProvider.GetParameter(CiFileTable.FieldFolderId);
            DataTable dataTable = new DataTable(CiFileTable.TableName);
            DBProvider.Fill(dataTable, sqlQuery, new IDbDataParameter[] { DBProvider.MakeParameter(CiFileTable.FieldFolderId, id)});
            if (id.Length == 0)
            {
                // 这里注意默认值
                DataRow dataRow = dataTable.NewRow();
                dataRow[CiFileTable.FieldEnabled] = 1;
                dataTable.Rows.Add(dataRow);
                dataTable.AcceptChanges();
            }
            this.GetFrom(dataTable);
            return dataTable;
        }
        #endregion

        #region public override int BatchSave(DataTable dataTable) 批量进行保存
        /// <summary>
        /// 批量进行保存
        /// </summary>
        /// <param name="dataTable">数据表</param>
        /// <returns>影响行数</returns>
        public override int BatchSave(DataTable dataTable)
        {
            int returnValue = 0;
            CiFileEntity fileEntity = new CiFileEntity();
            foreach (DataRow dataRow in dataTable.Rows)
            {
                // 删除状态
                if (dataRow.RowState == DataRowState.Deleted)
                {
                    string id = dataRow[CiFileTable.FieldId, DataRowVersion.Original].ToString();
                    if (id.Length > 0)
                    {
                        returnValue += this.Delete(id);
                    }
                }
                // 被修改过
                if (dataRow.RowState == DataRowState.Modified)
                {
                    string id = dataRow[CiFileTable.FieldId, DataRowVersion.Original].ToString();
                    if (id.Length > 0)
                    {
                        fileEntity.GetFrom(dataRow);
                        // 判断是否允许编辑
                        returnValue += this.UpdateEntity(fileEntity);
                    }
                }
                // 添加状态
                if (dataRow.RowState == DataRowState.Added)
                {
                    fileEntity.GetFrom(dataRow);
                    returnValue += this.AddEntity(fileEntity).Length > 0 ? 1 : 0;
                }
                if (dataRow.RowState == DataRowState.Unchanged)
                {
                    continue;
                }
                if (dataRow.RowState == DataRowState.Detached)
                {
                    continue;
                }
            }
            return returnValue;
        }
        #endregion

        #region public string Add(string folderId, string fileName, byte[] file, string category, bool enabled, out string statusCode) 添加文件
        /// <summary>
        /// 添加文件
        /// </summary>
        /// <param name="folderId">文件夹主键</param>
        /// <param name="fileName">文件名</param>
        /// <param name="file">文件</param>
        /// <param name="category">文件分类</param>
        /// <param name="enabled">有效</param>
        /// <param name="statusCode">状态</param>
        /// <returns>主键</returns>
        public string Add(string folderId, string fileName, byte[] file, string description, string category, bool enabled, out string statusCode)
        {
            return this.Add(folderId, fileName, null, file, description, category, enabled, out statusCode);
        }
        #endregion

        #region public string Add(string folderId, string fileName, byte[] file, string category, bool enabled, out string statusCode) 添加文件
        /// <summary>
        /// 添加文件
        /// </summary>
        /// <param name="folderId">文件夹主键</param>
        /// <param name="fileName">文件名</param>
        /// <param name="file">文件</param>
        /// <param name="category">文件分类</param>
        /// <param name="enabled">有效</param>
        /// <param name="statusCode">状态</param>
        /// <returns>主键</returns>
        public string Add(string folderId, string fileName, string file, string description, string category, bool enabled, out string statusCode)
        {
            return this.Add(folderId, fileName, file, null, description, category, enabled, out statusCode);
        }
        #endregion

        #region private string Add(string folderId, string fileName, string file, byte[] byteFile, string category, bool enabled, out string statusCode) 添加文件
        /// <summary>
        /// 添加文件
        /// </summary>
        /// <param name="folderId">文件夹主键</param>
        /// <param name="fileName">文件名</param>
        /// <param name="file">文件</param>
        /// <param name="category">文件分类</param>
        /// <param name="enabled">有效</param>
        /// <param name="statusCode">状态</param>
        /// <returns>主键</returns>
        private string Add(string folderId, string fileName, string file, byte[] byteFile, string description, string category, bool enabled, out string statusCode)
        {
            statusCode = string.Empty;
            CiFileEntity fileEntity = new CiFileEntity();
            fileEntity.FolderId = folderId;
            fileEntity.FileName = fileName;
            fileEntity.FileContent = byteFile;
            fileEntity.Description = description;
            fileEntity.Category = category;
            fileEntity.Enabled = enabled ? 1:0;
            string returnValue = string.Empty;
            // 检查是否重复
            if (this.Exists(CiFileTable.FieldFolderId, fileEntity.FolderId, CiFileTable.FieldFileName, fileEntity.FileName))
            {
                // 名称已重复
                statusCode = StatusCode.ErrorNameExist.ToString();
            }
            else
            {
                returnValue = this.AddEntity(fileEntity);
                // 运行成功
                statusCode = StatusCode.OKAdd.ToString();
            }
            return returnValue;
        }
        #endregion

        #region public string Add(BaseNewsEntity fileEntity, out string statusCode) 添加文件
        /// <summary>
        /// 添加文件
        /// </summary>
        /// <param name="folderId">文件夹主键</param>
        /// <param name="fileName">文件名</param>
        /// <param name="file">文件</param>
        /// <param name="category">文件分类</param>
        /// <param name="enabled">有效</param>
        /// <param name="statusCode">状态</param>
        /// <returns>主键</returns>
        public string Add(CiFileEntity fileEntity, out string statusCode)
        {
            statusCode = string.Empty;
            string returnValue = string.Empty;
            // 检查是否重复
            string[] names = new string[] { CiFileTable.FieldFolderId, CiFileTable.FieldFileName, CiFileTable.FieldDeleteMark };
            Object[] values = new object[] { fileEntity.FolderId, fileEntity.FileName, 0 };
            if (this.Exists(names, values))
            {
                // 名称已重复
                statusCode = StatusCode.ErrorNameExist.ToString();
            }
            else
            {
                returnValue = this.AddEntity(fileEntity);
                // 运行成功
                statusCode = StatusCode.OKAdd.ToString();
            }
            return returnValue;
        }
        #endregion

        #region public int Update(CiFileTable fileEntity, out string statusCode) 更新
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="fileEntity">文件夹的基类表结构定义</param>
        /// <param name="statusCode">状态返回码</param>
        /// <returns>影响行数</returns>
        public int Update(CiFileEntity fileEntity, out string statusCode)
        {
            int returnValue = 0;
            //if (DbLogic.IsModifed(DBProvider, CiFileTable.TableName, fileEntity.Id, fileEntity.ModifiedUserId, fileEntity.ModifiedOn))
            //{
            //    // 数据已经被修改
            //    statusCode = StatusCode.ErrorChanged.ToString();
            //}
            //else
            //{
                // 检查文件夹名是否重复
            if (this.Exists(CiFileTable.FieldFolderId, fileEntity.FolderId, CiFileTable.FieldFileName, fileEntity.FileName, fileEntity.Id))
                {
                    // 文件夹名已重复
                    statusCode = StatusCode.ErrorNameExist.ToString();
                }
                else
                {
                    returnValue = this.UpdateEntity(fileEntity);
                    if (returnValue == 1)
                    {
                        // 运行成功
                        statusCode = StatusCode.OKUpdate.ToString();
                    }
                    else
                    {
                        statusCode = StatusCode.ErrorDeleted.ToString();
                    }
                }
            //}
            return returnValue;
        }
        #endregion

        public int Update(string id, string folderId, string fileName, string description, bool enabled, out string statusCode)
        {
            statusCode = string.Empty;
            SQLBuilder sqlBuilder = new SQLBuilder(DBProvider);
            sqlBuilder.BeginUpdate(CiFileTable.TableName);
            sqlBuilder.SetValue(CiFileTable.FieldFolderId, folderId);
            sqlBuilder.SetValue(CiFileTable.FieldFileName, fileName);
            sqlBuilder.SetValue(CiFileTable.FieldEnabled, enabled);            
            sqlBuilder.SetValue(CiFileTable.FieldDescription, description);
            sqlBuilder.SetValue(CiFileTable.FieldModifyUserId, UserInfo.Id);
            sqlBuilder.SetValue(CiFileTable.FieldModifiedBy, UserInfo.RealName);
            sqlBuilder.SetDBNow(CiFileTable.FieldModifiedOn);
            sqlBuilder.SetWhere(CiFileTable.FieldId, id);
            int returnValue = sqlBuilder.EndUpdate();
            if (returnValue > 0)
            {
                statusCode = StatusCode.OKUpdate.ToString();
            }
            else
            {
                statusCode = StatusCode.ErrorDeleted.ToString();
            }
            return returnValue;
        }

        public int UpdateFile(string id, string fileName, byte[] file)
        {
            SQLBuilder sqlBuilder = new SQLBuilder(DBProvider);
            sqlBuilder.BeginUpdate(CiFileTable.TableName);
            sqlBuilder.SetValue(CiFileTable.FieldFileName, fileName);
            if (file != null)
            {
                sqlBuilder.SetValue(CiFileTable.FieldFileContent, file);
                sqlBuilder.SetValue(CiFileTable.FieldFileSize, file.Length);
            }
            sqlBuilder.SetValue(CiFileTable.FieldModifyUserId, UserInfo.Id);
            sqlBuilder.SetValue(CiFileTable.FieldModifiedBy, UserInfo.RealName);
            sqlBuilder.SetDBNow(CiFileTable.FieldModifiedOn);
            sqlBuilder.SetWhere(CiFileTable.FieldId, id);
            return sqlBuilder.EndUpdate();
        }

        public int UpdateFile(string id, string fileName, byte[] file, out string statusCode)
        {
            statusCode = string.Empty;
            int returnValue = this.UpdateFile(id, fileName, file);
            if (returnValue > 0)
            {
                statusCode = StatusCode.OKUpdate.ToString();
            }
            else
            {
                statusCode = StatusCode.ErrorDeleted.ToString();
            }
            return returnValue;
        }

        #region public DataTable Search(string searchValue) 查询
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="search">查询</param>
        /// <returns>数据表</returns>
        public DataTable Search(string searchValue)
        {
            return this.Search(string.Empty, searchValue);
        }
        #endregion

        public DataTable Search(string userId, string searchValue)
        {
            return this.Search(userId, string.Empty, searchValue);
        }

        #region public DataTable Search(string userId, string categoryCode, string searchValue) 查询
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="userId">用户主键</param>
        /// <param name="category">目录</param>
        /// <param name="searchValue">查询条件</param>
        /// <param name="deletionStateCode">删除标志</param>
        /// <returns>数据表</returns>
        public DataTable Search(string userId, string category, string searchValue)
        {
            return Search(userId, category, searchValue, null, null);
        }
        #endregion

        public DataTable Search(string userId, string category, string searchValue, bool? enabled, bool? deletionMark)
        {
            // 一、这里是将Boolean值转换为int类型。
            int delete = 0;
            if (deletionMark != null)
            {
                delete = (bool)deletionMark ? 1 : 0;
            }

            // 二、这里是开始进行动态SQL语句拼接，字段名、表明都进行了常量定义，表名字段名发生变化时，很容易就知道程序哪里都调用了这些。
            string sqlQuery = string.Empty;
            sqlQuery = " SELECT " + CiFileTable.FieldId
                    + "        ," + CiFileTable.FieldFolderId
                    + "        ," + CiFileTable.FieldCategory
                    + "        ," + CiFileTable.FieldFileName
                    + "        ," + CiFileTable.FieldFilePath
                    + "        ," + CiFileTable.FieldFileSize
                    + "        ," + CiFileTable.FieldReadCount
                    + "        ," + CiFileTable.FieldDescription
                    + "        ," + CiFileTable.FieldEnabled
                    + "        ," + CiFileTable.FieldDeleteMark
                    + "        ," + CiFileTable.FieldSortCode
                    + "        ," + CiFileTable.FieldCreateUserId
                    + "        ," + CiFileTable.FieldCreateBy
                    + "        ," + CiFileTable.FieldCreateOn
                    + "        ," + CiFileTable.FieldModifyUserId
                    + "        ," + CiFileTable.FieldModifiedBy
                    + "        ," + CiFileTable.FieldModifiedOn
                    + " FROM " + this.CurrentTableName
                    + " WHERE " + CiFileTable.FieldDeleteMark + " = " + delete;

            if (enabled != null)
            {
                int isEnabled = (bool)enabled ? 1 : 0;
                sqlQuery += " AND " + CiFileTable.FieldEnabled + " = " + isEnabled;
            }
            // 三、我们认为 userId 这个查询条件是安全，不是人为输入的参数，所以直接进行了SQL语句拼接
            if (!String.IsNullOrEmpty(userId))
            {
                sqlQuery += " AND " + CiFileTable.FieldCreateUserId + " = " + userId;
            }
            /*
            if (!String.IsNullOrEmpty(folderId))
            {
                sqlQuery += " AND " + BaseNewsEntity.FieldCategoryCode + " = " + folderId;
            }
            */

            if (!String.IsNullOrEmpty(category))
            {
                sqlQuery += " AND " + CiFileTable.FieldCategory + " = '" + category + "'";
            }

            // 四、这里是进行参数化的准备，因为是多个不确定的查询参数，所以用了List。
            List<IDbDataParameter> dbParameters = new List<IDbDataParameter>();

            // 五、这里看查询条件是否为空
            searchValue = searchValue.Trim();
            if (!String.IsNullOrEmpty(searchValue))
            {
                // 六、这里是进行支持多种数据库的参数化查询
                sqlQuery += " AND (" + CiFileTable.FieldFileName + " LIKE " + DBProvider.GetParameter(CiFileTable.FieldFileName);
                sqlQuery += " OR " + CiFileTable.FieldCategory + " LIKE " + DBProvider.GetParameter(CiFileTable.FieldCategory);
                sqlQuery += " OR " + CiFileTable.FieldCreateBy + " LIKE " + DBProvider.GetParameter(CiFileTable.FieldCreateBy);
                sqlQuery += " OR " + CiFileTable.FieldFileContent + " LIKE " + DBProvider.GetParameter(CiFileTable.FieldFileContent);
                sqlQuery += " OR " + CiFileTable.FieldDescription + " LIKE " + DBProvider.GetParameter(CiFileTable.FieldDescription) + ")";

                // 七、这里是判断，用户是否已经输入了%
                if (searchValue.IndexOf("%") < 0)
                {
                    searchValue = "%" + searchValue + "%";
                }

                // 八、这里生成支持多数据库的参数
                dbParameters.Add(DBProvider.MakeParameter(CiFileTable.FieldFileName, searchValue));
                dbParameters.Add(DBProvider.MakeParameter(CiFileTable.FieldCategory, searchValue));
                dbParameters.Add(DBProvider.MakeParameter(CiFileTable.FieldCreateBy, searchValue));
                dbParameters.Add(DBProvider.MakeParameter(CiFileTable.FieldFileContent, searchValue));
                dbParameters.Add(DBProvider.MakeParameter(CiFileTable.FieldDescription, searchValue));
            }
            sqlQuery += " ORDER BY " + CiFileTable.FieldSortCode + " DESC ";

            // 九、这里是将List转换为数组，进行数据库查询
            return DBProvider.Fill(sqlQuery, dbParameters.ToArray());
        }


        /// <summary>
        /// 移动（要考虑文件的覆盖问题，文件名重复了，需要覆盖文件的）
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="folderId">文件夹主键</param>
        /// <returns>影响行数</returns>
        public int MoveTo(string id, string folderId)
        {
            // 有重名的文件，需要进行覆盖
            string fileName = this.GetProperty(id, CiFileTable.FieldFileName);
            this.Delete(CiFileTable.FieldFolderId, folderId, CiFileTable.FieldFileName, fileName);
            return this.SetProperty(id, CiFileTable.FieldFolderId, folderId);
        }

        /// <summary>
        /// 按目录删除文件
        /// </summary>
        /// <param name="folderId">文件夹主键</param>
        /// <returns>影响行数</returns>
        public int DeleteByFolder(string folderId)
        {
            return this.Delete(CiFileTable.FieldFolderId, folderId);
        }

        #region public Double GetSumFileSize() 服务器已用空间(单位Byte)
        /// <summary>
        /// 服务器已用空间(单位Byte)
        /// </summary>
        public Double GetSumFileSize()
        {
            // 已用空间
            string sqlQuery = " SELECT SUM(FileSize) FROM CiFile ";
            return Double.Parse(DBProvider.ExecuteScalar(sqlQuery).ToString());
        }
        #endregion

        #region public Double GetSumFileSize(string userId)
        /// <summary>
        /// 当前用户已用空间
        /// </summary>
        public Double GetSumFileSize(string userId)
        {
            // 当前用户已用空间
            string sqlQuery = " SELECT SUM(FileSize) FROM CiFile WHERE CreateUserId='" + userId + "'";
            return Double.Parse(DBProvider.ExecuteScalar(sqlQuery).ToString());
        }
        #endregion

        #region public Double GetSumFileSize(bool enabled) 服务器已用空间(单位Byte)
        /// <summary>
        /// 服务器已用空间(单位Byte)
        /// </summary>
        public Double GetSumFileSize(bool enabled)
        {
            // 已用空间
            string sqlQuery = " SELECT SUM(FileSize) FROM CiFile WHERE Enabled = ";
            sqlQuery += enabled ? "1" : "0";
            return Double.Parse(DBProvider.ExecuteScalar(sqlQuery).ToString());
        }
        #endregion

        #region public int GetFileCount() 文件数量
        /// <summary>
        /// 文件数量
        /// </summary>
        public int GetFileCount()
        {
            // 文件数量
            string sqlQuery = " SELECT COUNT(*) FROM CiFile ";
            return int.Parse(DBProvider.ExecuteScalar(sqlQuery).ToString());
        }
        #endregion

        #region public int GetFileCount() 文件数量
        /// <summary>
        /// 文件数量
        /// </summary>
        public int GetFileCount(bool enabled)
        {
            // 文件数量
            string sqlQuery = " SELECT COUNT(*) FROM CiFile WHERE Enabled = ";
            sqlQuery += enabled ? "1" : "0";
            return int.Parse(DBProvider.ExecuteScalar(sqlQuery).ToString());
        }
        #endregion

        #region public int GetFileCount() 文件数量
        /// <summary>
        /// 文件数量
        /// </summary>
        public int GetFileCount(string userId)
        {
            // 文件数量
            string sqlQuery = " SELECT COUNT(*) FROM CiFile WHERE CreateUserId='" + userId + "'";
            return int.Parse(DBProvider.ExecuteScalar(sqlQuery).ToString());
        }
        #endregion

        #region public int GetFlowmeter() 文件总的流量
        /// <summary>
        /// 文件总的流量
        /// </summary>
        public int GetFlowmeter()
        {
            // 文件数量
            string sqlQuery = "SELECT SUM(FileSize * ReadCount) FROM CiFile ";
            return int.Parse(DBProvider.ExecuteScalar(sqlQuery).ToString());
        }
        #endregion

        #region public int GetFlowmeter(string userId) 文件总的流量
        /// <summary>
        /// 文件总的流量
        /// </summary>
        public int GetFlowmeter(string userId)
        {
            // 文件数量
            string sqlQuery = "SELECT SUM(FileSize * ReadCount) FROM CiFile "
                            + " WHERE CreateUserId='" + userId + "'";
            return int.Parse(DBProvider.ExecuteScalar(sqlQuery).ToString());
        }
        #endregion

        #region public int GetFileCount(string folderId, string userId) 文件夹中文件数量
        /// <summary>
        /// 文件夹中文件数量
        /// </summary>
        public int GetFileCount(string folderId, string userId)
        {
            // 文件数量
            string sqlQuery = " SELECT SUM(FileSize * ReadCount) FROM CiFile "
                            + " WHERE CreateUserId='" + userId + "'"
                            + " AND " + CiFolderTable.FieldParentId + " = '" + folderId + "'";
            return int.Parse(DBProvider.ExecuteScalar(sqlQuery).ToString());
        }
        #endregion       
        
    }
}
